package com.kun.hanlp.config;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.utility.Predefine;
import com.kun.hanlp.listener.HanlpListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kun.li
 */
@EnableConfigurationProperties(HanlpProperties.class)
@Slf4j
public class HanlpAutoConfiguration {

    @Autowired
    private HanlpProperties hanlpProperties;


    @Bean
    @ConditionalOnProperty(prefix = "hanlp", name = "file.watch.enable", matchIfMissing = true)
    public HanlpListener hanlpListener() {
        return new HanlpListener();
    }

    @Bean
    public Segment segment() {
        return HanLP.newSegment();
    }

    // 必须优先加载 适用于在项目外动态配置hanlp路径
    @PostConstruct
    public void init() {
        String type = hanlpProperties.getType();
        if ("0".equals(type)) {
            customHanlpPath();
        } else {
            hanlpPropertiesPath();
        }

    }


    public void customHanlpPath() {
        String hanlpPropertiesRoot = hanlpProperties.getRoot();
        if (!StringUtils.hasText(hanlpPropertiesRoot)) {
            log.error("hanlp的主目录必须填写");
            return;
        }
        System.setProperty("HANLP_ROOT", hanlpPropertiesRoot);
        List<String> customDictionPath = hanlpProperties.getCustomDictionPath();
        List<String> buildCustomDictionPathList = customDictionPath.stream()
                .map(path -> hanlpPropertiesRoot + path).collect(Collectors.toList());
        if (hanlpProperties.isDebug()) {
            HanLP.Config.enableDebug();
        }
        // 自定义词典路径
        HanLP.Config.CustomDictionaryPath = buildCustomDictionPathList.toArray(new String[]{});
    }

    //指定hanlp路径方式
    public void hanlpPropertiesPath() {
        Predefine.HANLP_PROPERTIES_PATH = hanlpProperties.getHaNlpPropertiesPath();
        log.info("HANLP_PROPERTIES_PATH:{}", Predefine.HANLP_PROPERTIES_PATH);
    }

}
